import { get, post, put, del } from './request'

// 收文登记分页查询 DTO
export interface ReceiveRegisterQueryDTO {
  sourceDocumentNumber?: string
  receiveDocumentNumber?: string
  receiveStepOrder?: number // 收文步骤顺序 0-空值查询 1-步骤1查询
  startTime?: string
  endTime?: string
  pageNum?: number
  pageSize?: number
  receiveDocumentSymbol?: string
  sourceDocumentTitle?: string
  currentUserId?: any // 当前用户ID（权限验证用）
}

// 收文记录简要类型
export interface ReceiveDocumentDistributeItem {
  id: number
  sourceDocumentNumber?: string
  receiveDocumentNumber?: string
  receiveDocumentSymbol?: string // 收文文号
  title?: string
  sourceDocumentTitle?: string
  sourceCompanyName?: string
  sourceDocumentUrgencyLevel?: string // 紧急程度
  senderName?: string
  createdAt?: string
  receiveDocumentTime?: string
  status?: string | number
  // 预览/下载相关可选字段
  attachmentId?: number
  fileUrl?: string
  fileName?: string
  documentUrl?: string
  // 流程步骤信息
  currentStepName?: string
  nextStepName?: string
  receiveStepOrder?: number
  sourceDocumentId?: number | null
}

// 分页查询收文记录（查看）
export function getReceiveRegisterPage(params: ReceiveRegisterQueryDTO) {
  return get<{
    records: ReceiveDocumentDistributeItem[]
    total: number
    current: number
    size: number
  }>('/receive/distributes/external', params)
}

// 删除手动登记收文
export function deleteReceiveRegister(id: number) {
  return get(`/receive/distributes/delete/${id}`)
}

// 获取收文附件
export function getAttachmentApi(documentId: number) {
  return get(`/receive/attachments/document/${documentId}/page`)
}

// 根据ID查询收文记录详情
export function getReceiveRegisterById(id: number) {
  return get<ReceiveDocumentDistributeItem>(`/receive/distributes/${id}`)
}

// 收文审批
export function approveReceiveRegister(id: number, approveData: any) {
  return post(`/receive/distributes/${id}/approve`, approveData)
}

// 根据角色获取人员列表
export function getUsersByRole(roleName: string) {
  return get(`/users/role/${roleName}`)
}

// 查询：按 bizId + stepOrder 取收文业务流程进度
export function getReceiveDocumentFlowByStep(bizId: number, stepOrder: number) {
  return get(`/receive/flow-progress/document/by-step`, { bizId, stepOrder })
}

// 根据角色ID查询用户列表
export function getUsersByRoleId(roleId: number) {
  return get(`/system/roles/${roleId}/users`)
}

// 选人提交：一次性把 bizId 与选中人员提交到后端
export function submitApprovers(payload: {
  bizId: number
  approvers: { id: number; name: string }[]
  opinion?: string
  decision?: string
  receiveStepName?: string
  receiveStepOrder?: number
}) {
  return post(`/receive/flow-progress/document/submit-approvers`, payload)
}

// 选人提交：科室办理时可以选择其他科室办理
export function submitDeptManageApprovers(payload: {
  bizId: number
  approvers: { id: number; name: string }[]
  receiveStepOrder?: number
}) {
  return post(`/receive/flow-progress/document/reassign-approvers`, payload)
}

// 协作办理 如果当前科室办理为协作 那么拒绝单独调接口
export function submitCooperateDistributeFlow(payload: {
  bizId: number
  approvers: { id: number; name: string }[]
  opinion?: string
  decision?: string
  receiveStepName?: string
  receiveStepOrder?: number
}) {
  return post(`/receive/flow-progress/document/special-reject`, payload)
}

// 按当前用户与操作角色查询我的待处理收文
export function getMyDistributesByRole() {
  return get(`/receive/distributes/mine`)
}

// 手动登记：手动录入收文信息
export function createReceiveDraftByHand(params: any) {
  return post(`/receive/distributes/create-with-files`, params, {
    header: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

// 确认登记：从 receive__document_flow_progress 复制数据到 receive_document_distribute
export function createReceiveDraft(bizId: number, params: any) {
  return post(`/receive/distributes/${bizId}/draft`, params)
}

// 确认登记：上传文件
export function createReceiveDraftAddFile(params: any) {
  return post(`/receive/attachments/upload`, params)
}

// 删除附件
export function deleteReceiveAttachment(attachmentId: number) {
  return del(`/receive/attachments/${attachmentId}`)
}

// 查询当前步骤的审批类型
export function getCurrentStepApprovalType(bizId: number, stepOrder: number) {
  return get(`/receive/flow-progress/document/approval-type`, { bizId, stepOrder })
}

// 获取我的收文列表
export function getMyReceiveDocuments(params: any) {
  return post('/receive/distributes/my-receive/external', params)
}

// 获取所有收文列表
export function getAllReceiveDocuments(params: any) {
  return post('/receive/distributes/all-receive', params)
}

// 获取内部单位收文列表
export function getInternalReceiveDocuments(params: any) {
  return post('/receive/distributes/all-receive/internal', params)
}

// 获取我的内部单位收文列表
export function getMyInternalReceiveDocuments(params: any) {
  return post('/receive/distributes/my-receive/internal', params)
}

// 标记内部收文为已读（使用PUT方法，与后端@PutMapping对应）
export function markInternalReceiveAsRead(receiveDocumentId: number) {
  return put(`/receive/document-receive/mark-read/${receiveDocumentId}`)
}

// 获取外部单位收文列表
export function getExternalReceiveDocuments(params: any) {
  return post('/receive/distributes/all-receive/external', params)
}

// 删除收文
export function deleteReceiveDocument(id: number) {
  return del(`/receive/distributes/${id}`)
}

// 归档收文
export function archiveReceiveDocument(
  id: number,
  archiveData: { approvalDeadline?: string; opinion?: string },
) {
  return post(`/receive/distributes/${id}/archive`, archiveData)
}

// 获取收文审批记录
export function getApprovalReceiveRecords(params: any) {
  return get('/receive/flow-progress/approved-documents', params)
}

// 获取流程记录（收文）
export function getReceiveFlow(data: any) {
  return get('/receive/approval-flow/by-biz', data)
}

// 获取流程记录（支持科室办理多记录显示）
export function getReceiveFlowRecords(bizId: number) {
  return get(`/receive/approval-flow/flow-records`, { bizId })
}

// 下载收文红头文件（通过后端接口下载，返回base64数据）
export function downloadReceiveDocument(documentId: number) {
  return get<{
    fileName: string
    fileType: string
    base64Data: string
    dataUrl: string
  }>(`/receive/distributes/${documentId}/download-document`)
}

// 创建或更新上级系统的公文查看记录
export function createDocumentViewSync(
  distributeId: number,
  syncData: {
    documentId: number
    documentTitle: string
    companyId: number
    companyName: string
    viewerName?: string
    viewerDeptName?: string
    viewStatus?: number
    viewedAt?: string
    createdAt?: string
  },
) {
  return post(`/receive/document-view-sync/${distributeId}/create-document-view`, syncData)
}
